<?php
/**
 * admin.php
 *
 * 后台处理
 * @author konakona
 * @date 2009-9-20
 */
class admin {
	/**
	* 管理员登陆
	*@param $_login 管理员表单提交的数据
	**/
	public static function adminlogin($_login){
            if(!self::isAdminOnline()){
                    $_login = k::escapeSQL($_login);
                    if($_POST['user']!='konakona'){
                        template::assign('errmsg','Sorry! Your name and the password is error.');
    			        template::display('../admin/login.html');
                    }else if(self::verifyPassword($_login['password'])){
                        self::adminloginip($_POST['user']);
                        $_SESSION['kona_admin']='konakona';
                        k::message('Welcome Admin!','admin.php');
                    }else{
                        template::assign('errmsg','Sorry! Your name and the password is error.');
    			        template::display('../admin/login.html');
                    }
            }
        }
    /**
     * 后台管理员退出
	*@return bool
     **/
	public static function adminlogout(){
		if(self::isAdminOnline()){session_destroy();k::message('Done,Return Home','index.php');}
	}
	/**
     * 后台操作员退出
	*@return bool
     **/
	public static function OT_logout(){
		if(self::isOTOnline()){session_destroy();k::message('Done,Return Home','index.php');}
	}
    /**
     * 获取管理员的salt值
     * @param $u_id Int
	*@return Int
     **/
	private static function getSalt($u_id){
		$salt = mysql::connect()->fetch_all("select salt from ".k::$config['TABLEPREFIX']."admins where id={$u_id}");
		return $salt[0]['salt'];
	}
	/**
	 * 记录管理员最后一次登陆的ip 
	 * @param  $username  string
	 */
	public static function adminloginip($username){
	   mysql::connect()->query("UPDATE `admins` SET `lasttime` = '".time()."',lastip = '".k::getip()."' WHERE username='{$username}'");
	}
    /**
     * 检测管理员是否在线
	 * @return bool
     **/
	public static function isAdminOnline(){
		if($_SESSION['kona_admin']=='konakona'){
			return true;
		}else{
			return false;
		}
	}
	/**
     * 检测操作员(OT)是否在线
	 * @return bool
     **/
	 public static function isOTOnline(){
		if($_SESSION['OT_admin']){
			return true;
		}else{
			return false;
		}
	 }
    /**
     * 验证密码
     * @param string $pwd
     * @return bool
     */
	private static function verifyPassword($pwd,$id=1){
		$salt = self::getSalt($id);
		$sqlpwd = md5(md5($pwd).$salt);
		$datapwd = mysql::connect()->fetch_all("select password from ".k::$config['TABLEPREFIX']."admins where password='{$sqlpwd}'");
		if(empty($datapwd[0]['password'])){
			return false;
		}else{
			return true;
		}
	}
    /**
     * 用户统计
	*@return int
     **/
    public static function getUserCount(){
        $usercount = mysql::connect()->fetch_all("select count(*) from ".k::$config['TABLEPREFIX']."members");
        return $usercount[0]['count(*)'];
    }
    /**
     * 获取用户
     * @param int $all　如果参数为１，寻找单笔数据，否则返回全部信息
     * @param int $u_id
     */
    public static function getUser($all=0,$u_id=''){
        if(!$all){
            $sql = "select * from ".k::$config['TABLEPREFIX']."admins where id!=1";

        }elseif(is_numeric($u_id)){
            $sql.=" and id={$u_id}";
        }
        $sql.=" ORDER BY id";
        return mysql::connect()->fetch_all($sql);
    }
	/**
	* 操作员登陆
	* @param array $_login 
	*/ 
	public static function OT_login($_login){
		if(!self::isOTOnline()){
				$_login = k::escapeSQL($_login);
				$id = mysql::connect()->fetch_all("select id from admins where username = '{$_login[user]}' and id!=1");
				if($id==NUll){
					template::assign('errmsg','Sorry! Your name and the password is error.');
					template::display('../admin/ot_login.html');
					exit;
				}
				if(self::verifyPassword($_login['password'],$id[0]['id'])){
					self::adminloginip($_login['user']);
					$_SESSION['OT_admin']=$_login['user'];
					k::message('Welcome Operator Admin!','ot.php');
				}else{
					template::assign('errmsg','Sorry! Your name and the password is error.');
					template::display('../admin/ot_login.html');
				}
            }
	}
	/**
     * 添加新的操作员
     * @param $_post 操作员form信息
     */
	public static function admin_add($_post){
		$username = trim($_post['username']);
		$pwd = trim($_post['pwd']);
		$salt = substr(uniqid(rand()), -6);
		$insertPWD = md5(md5($pwd).$salt);
		$sql = "INSERT INTO admins values('','{$username}','{$insertPWD}','{$salt}','".k::getip()."',".time().")";
		mysql::connect()->query($sql);
		k::message('添加成功，可以尝试登陆！','admin.php?action=admin-list');
	}
	/**
     * 修改操作员密码
     * @param $_post 操作员form信息
     */
	public static function admin_edit($_post){
		$salt = self::getSalt($_post[id]);
		$pwd = trim($_post[pwd]);
		$insertPWD=md5(md5($pwd).$salt);
		$sql = "UPDATE `admins` SET `password` = '{$insertPWD}' WHERE `id` ={$_post[id]}";
		mysql::connect()->query($sql);
		return true;
		
	}
    /**
     * 删除一个或多个用户用户
     * @param mixed $id
     */
    public static function delUser($id){
        mysql::connect()->query("DELETE FROM ".k::$config['TABLEPREFIX']."admins where id='{$id}'");
        k::message('删除操作员完毕','javascript:history.go(-1);');
    }
    /**
     * 保存基本设置
     * @param array $setting
	* 替换掉必要数据后存入文件
     */
	public static function saveSetting($setting){
		if(!preg_match("/^http:\/\/[^\s]*/is",$setting['weburl']))
			k::message('网站网址不正确','javascript:history.go(-1);');
		if(!is_numeric($setting['last_updated']))
			k::message('最近更新篇幅请输入数字','javascript:history.go(-1);');
		if(!is_numeric($setting['pmsendregdays']))
			k::message('发短消息最少注册天数不是数字','javascript:history.go(-1);');
		if($setting['last_updated']>25)
			k::message('最近更新篇数设置不正确，请参阅描述','javascript:history.go(-1);');
		include('config.php');
		$config['WEB_NAME'] = $setting['webname'];
		$config['PMSENDREGDAYS'] = $setting['pmsendregdays'];
		$config['WEB_URL'] = $setting['weburl'];
		$config['DEFAULT_STYLE'] = $setting['webstyle'];
		$config['INDEX_LAST_UPDATED'] = $setting['last_updated'];
		$config['WEB_ICP'] = $setting['webicp'];
		$config['WEB_ADMIN_EMAIL'] = $setting['webadminemail'];
		$config['WEB_SENDPMCODE'] = $setting['sendpmseccode'];
		$config['REGONLYEMAIL'] = $setting['regonlyemail'];
		$config['SENDREGMAIL'] = $setting['sendregmail'];
		$config['REGSECCODE'] = $setting['regseccode'];
		$str = "<?php\n"."\$config=array(";
		foreach($config as $k=>$v){
			$str .="\n\t\"".$k."\"=>\"$v\",";
		}
		$str =substr_replace($str,"",-1);
		$str .= "\n); \n return \t";
		$str .='$config;   ?>';
		k::write('config.php',$str,"wb+")?k::message('成功保存基本设置','javascript:history.go(-1);'):k::message('文件设置失败,请检查配置文件是否存在','javascript:history.go(-1);');
	}
	/**
     * 提取后台基本设置
     * @return array $setting
	 * 打开config.php提取出指定的内容并返回
     */
	public static function getSetting(){
		include("config.php");
		return $config;
	}
	/**
     * 保存新的友情链接
     * @param array $link
     */
	public static function addLink($link){
		$link = k::escapeSQL($link);
		if(!preg_match('/^(http:\/\/)/',$link['linkurl'])){
			k::message('这不是一个合法的网址','javascript:history.go(-1);');
		}
		mysql::connect()->query("INSERT INTO ".k::$config['TABLEPREFIX']."link values('','{$link[linkname]}','{$link[linkinfo]}','{$link[linkurl]}')");
		k::message('成功添加链接','javascript:history.go(-1);');
	}
	/**
     * 获取友情链接
     * @return array
     */
	public static function getLink(){
		return mysql::connect()->fetch_all("select * from ".k::$config['TABLEPREFIX']."link");
	}
	/**
     * 删除友情链接
     * @param array $link
     */
	public static function delLink($link){
		foreach($link['delete'] as $r){
           mysql::connect()->query("DELETE FROM ".k::$config['TABLEPREFIX']."link where l_id='{$r}'");
        }
       k::message('删除链接完毕','javascript:history.go(-1);');
	}
	
}